package com.chuanye.jiguangimdemo.activitys;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.chuanye.jiguangimdemo.R;
import com.chuanye.jiguangimdemo.database.UserEntry;
import com.chuanye.jiguangimdemo.sharepreference.SharePreferenceManager;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.RequestCallback;
import cn.jpush.im.android.api.model.DeviceInfo;
import cn.jpush.im.android.api.model.UserInfo;

public class LoginActivity extends BaseActivity implements View.OnClickListener{
    private static final String TAG = "LoginActivity";
    private Context mContext;

    private EditText login_username_et;
    private EditText login_password_et;
    private TextView login_jp_register_tv;
    private Button login_exit_btn;
    private Button login_logging_btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mContext = this;

        initView();
    }

    private void initView() {
        login_username_et = findViewById(R.id.login_username_et);//用户名
        login_password_et = findViewById(R.id.login_password_et);//密码
        login_logging_btn = findViewById(R.id.login_logging_btn);//登录
        login_logging_btn.setOnClickListener(this);
        login_jp_register_tv = findViewById(R.id.login_jp_register_tv);//注册
        login_jp_register_tv.setOnClickListener(this);
        login_exit_btn = findViewById(R.id.login_exit_btn);//退出登录
        login_exit_btn.setOnClickListener(this);

        //设置用户名和密码
        String userName = SharePreferenceManager.getCachedUsername();
        String password = SharePreferenceManager.getCachedPsw();
        login_username_et.setText(userName);
        login_password_et.setText(password);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.login_logging_btn:
                final String username = login_username_et.getText().toString().trim();
                final String password  = login_password_et.getText().toString().trim();
                if (TextUtils.isEmpty(username)|| TextUtils.isEmpty(password)){
                    Toast.makeText(mContext,"用户名和密码不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (username.length() < 4){
                    Toast.makeText(mContext,"用户名长度不能小于4",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (password.length() < 4){
                    Toast.makeText(mContext,"密码长度不能小于4",Toast.LENGTH_SHORT).show();
                    return;
                }
                String password1 = md5(password);
                //登录
                /*JMessageClient.login(username, password1, new BasicCallback() {
                    @Override
                    public void gotResult(int responseCode, String responseMessage) {
                        Log.i(TAG,"登录：返回编号:"+responseCode +" ,返回数据:"+responseMessage);
                        if (responseCode == 871201 && responseMessage.equals("Get response timeout,please try again later.")){
                            Toast.makeText(mContext,"响应超时，请稍后再试",Toast.LENGTH_SHORT).show();

                        }else if (responseCode == 0 && responseMessage.equals("Success")){
                            Toast.makeText(mContext,"登录成功",Toast.LENGTH_SHORT).show();
                        }

                    }
                });*/
                JMessageClient.login(username,password, new RequestCallback<List<DeviceInfo>>() {
                            @Override
                            public void gotResult(int responseCode, String responseMessage, List<DeviceInfo> deviceInfos) {
                                Log.i(TAG,"登录：返回编号:"+responseCode +" ,返回数据:"+responseMessage+" ,deviceInfos:"+deviceInfos);
                                if (responseCode == 871201 && responseMessage.equals("Get response timeout,please try again later.")){
                                    Toast.makeText(mContext,"响应超时，请稍后再试",Toast.LENGTH_SHORT).show();

                                }else if (responseCode == 801004 && responseMessage.equals("invalid password")){
                                    Toast.makeText(mContext,"密码错误",Toast.LENGTH_SHORT).show();
                                }else if (responseCode == 801003 && responseMessage.equals("user not exist")){
                                    Toast.makeText(mContext,"用户不存在",Toast.LENGTH_SHORT).show();
                                }else if (responseCode == 0){
                                    Toast.makeText(mContext,"登录成功",Toast.LENGTH_SHORT).show();
                                    //保存用户名密码
                                    SharePreferenceManager.setCachedUsername(username);
                                    SharePreferenceManager.setCachedPsw(password);
                                    UserInfo myInfo = JMessageClient.getMyInfo();
                                    File avatarFile = myInfo.getAvatarFile();
                                    //登陆成功,如果用户有头像就把头像存起来,没有就设置null
                                    if (avatarFile != null) {
                                        SharePreferenceManager.setCachedAvatarPath(avatarFile.getAbsolutePath());
                                    } else {
                                        SharePreferenceManager.setCachedAvatarPath(null);
                                    }
                                    String username = myInfo.getUserName();
                                    String appKey = myInfo.getAppKey();
                                    //保存数据库
                                    UserEntry user = UserEntry.getUser(username, appKey);
                                    if (null == user) {
                                        user = new UserEntry(username, appKey);
                                        user.save();
                                    }
                                    //跳转到首页
                                    Intent intent = new Intent(mContext, HomeActivity.class);
                                    startActivity(intent);
                                    finish();

                                    /*if (deviceInfos != null && deviceInfos.size() > 0){
                                        Long deviceID =  deviceInfos.get(0).getDeviceID();//获取设备ID
                                        PlatformType platformType = deviceInfos.get(0).getPlatformType();//获取设备所属平台类型
                                        int onlinestatus = deviceInfos.get(0).getOnlineStatus();//获取设备在线状态，0不在线，1在线
                                        boolean islogin = deviceInfos.get(0).isLogin();//判断设备当前是否处于登陆状态, true:登陆，false:登出
                                        int lastlogintime = deviceInfos.get(0).getLastLoginTime();//获取设备最近一次登陆时间，单位-秒
                                        int flag = deviceInfos.get(0).getFlag();//默认为0，1表示该设备被当前登录设备踢出

                                        Log.i(TAG,"登录：设备ID:"+deviceID+" ,设备所属平台："
                                                +platformType.toString()+" ,设备在线状态:"+onlinestatus+" ,是否在线："
                                                +islogin+",最近一次登陆时间:"+lastlogintime+" ,1表示该设备被当前登录设备踢出:"+flag);
                                    }*/
                                }
                            }
                        }
                );
                break;
            case R.id.login_jp_register_tv:
                Intent intent = new Intent(mContext, RegisterActivity.class);
                startActivity(intent);

                break;
            case R.id.login_exit_btn://退出
                JMessageClient.logout();
                break;
        }
    }

    /**
     * md5加密
     * @param string
     * @return
     */
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
